package vcp.views;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.sql.Date;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
import client.Message;
import com.itextpdf.text.DocumentException;
import db.parking.beans.Complaints;
import db.parking.beans.Orders;
import db.parking.beans.ParkingLot;
import db.parking.beans.SaveDisableParking;
import db.parking.beans.WeeklyStatistics;
import vcp.common.AbstractView;
import vcp.common.IView;
import vcp.gui.components.VCPScrollTable;
import vcp.gui.panels.networkmanager.PnlLotsStats;
import vcp.gui.panels.networkmanager.PnlMonthlyReports;
import vcp.gui.panels.networkmanager.PnlQuarterReports;
import vcp.gui.panels.networkmanager.PnlReports;
import vcp.gui.panels.parkingmanager.PnlReportManagement;
import vcp.pdf.LocationsState;


/**
 * Reports View
 *
 */
public class ReportsView extends AbstractView implements IView, Observer {
	PnlReportManagement pnlReportManagement;
	PnlReports pnlReports;
	PnlLotsStats pnlLotsStats;
	PnlQuarterReports pnlQuarterReports;
	PnlMonthlyReports pnlMonthlyReports;
	Object controller;

	public ReportsView() {
		pnlReportManagement = new PnlReportManagement();
		pnlReports = new PnlReports();
		pnlLotsStats = new PnlLotsStats();
		pnlQuarterReports = new PnlQuarterReports();
		pnlMonthlyReports = new PnlMonthlyReports();
	}

	@Override
	public void update(Observable o, Object arg) {
		Message msg = (Message) arg;
		String func = msg.getMsg();
        if(func.equals("CreateQuarterReport") && msg.isStatus()){
        	JOptionPane.showMessageDialog(null,
					"Report generated sucessfully!", null,
					JOptionPane.INFORMATION_MESSAGE);
        }else if (func.equals("GetLotByLotNum") && msg.isStatus()) {
			ParkingLot pl = (ParkingLot) msg.getObj();
			LocationsState lstate = new LocationsState();
			try {
				lstate.createPdf(pl);
				if (lstate.getPdfStatus() == 2) {
					JOptionPane.showMessageDialog(null,
							"Report exported sucessfully!", null,
							JOptionPane.INFORMATION_MESSAGE);
				} else if (lstate.getPdfStatus() == 1) {
					JOptionPane.showMessageDialog(null, "Export cancelled!",
							null, JOptionPane.INFORMATION_MESSAGE);
				} else if (lstate.getPdfStatus() == 0) {
					JOptionPane.showMessageDialog(null,
							"Error occured creating pdf ...", "Pdf error",
							JOptionPane.ERROR_MESSAGE);
				}

			} catch (IOException e) {
				e.printStackTrace();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		} else if (func.equals("GetQuarterReport") && msg.isStatus()) {
			Object mdata = msg.getObj();
			VCPScrollTable table = null;
			pnlQuarterReports.getPnlTable().removeAll();
			pnlQuarterReports.getPnlTable().revalidate();
			if (mdata instanceof Orders[]) {
				Orders[] orders = (Orders[]) mdata;
				String[] onames = { "Order ID", "User ID", "Type",
						"Car number"};

				DefaultTableModel dtm = new DefaultTableModel(null, onames);
				table = new VCPScrollTable(5, dtm);
				if (orders.length > 0) {
					Object obj[] = new Object[onames.length];
					for (int i = 0; i < orders.length; i++) {
						Orders order = orders[i];
						obj[0] = order.getOid();
						obj[1] = order.getUid();
						obj[2] = order.getType();
						obj[3] = order.getCarNo();
//						obj[4] = order.getStartTime();
//						obj[5] = order.getLeaveTime();
						table.getDtm().addRow(obj);
					}
				}
				JPanel cntPane = new JPanel();
				cntPane.setLayout(new GridLayout(1,1));
				cntPane.add(new JLabel("Total orders : "+new Integer(orders.length).toString()));
				pnlQuarterReports.getPnlTable().add(cntPane,BorderLayout.PAGE_START);
				pnlQuarterReports.getPnlTable().add(table, BorderLayout.CENTER);
			} else if (mdata instanceof Complaints[]) {
				Complaints[] complaints = (Complaints[]) mdata;
				String[] cnames = { "Received", "Customer ID", "Title",
						"Status" };
				DefaultTableModel dtm = new DefaultTableModel(null, cnames);
				table = new VCPScrollTable(5, dtm);
				if (complaints.length > 0) {
					Object obj[] = new Object[cnames.length];
					for (int i = 0; i < complaints.length; i++) {
						Complaints compl = complaints[i];
						obj[0] = compl.getTimestamp();
						obj[1] = compl.getCustomerID();
						obj[2] = compl.getTitle();
						obj[3] = compl.getStatus();
						table.getDtm().addRow(obj);
					}
				}
				JPanel cntPane = new JPanel();
				cntPane.setLayout(new GridLayout(1,1));
				cntPane.add(new JLabel("Total complaints : "+new Integer(complaints.length).toString()));
				pnlQuarterReports.getPnlTable().add(cntPane,BorderLayout.PAGE_START);
				pnlQuarterReports.getPnlTable().add(table, BorderLayout.CENTER);
			} else if (mdata instanceof SaveDisableParking[]) {
				SaveDisableParking[] disabledParkings = (SaveDisableParking[]) mdata;
				String[] cnames = { "Lot#", "Employee ID", "DisableStart",
						"DisableEnd", "x", "y", "z", "status" };
				DefaultTableModel dtm = new DefaultTableModel(null, cnames);
				table = new VCPScrollTable(5, dtm);
				if (disabledParkings.length > 0) {
					Object obj[] = new Object[cnames.length];
					for (int i = 0; i < disabledParkings.length; i++) {
						SaveDisableParking dpk = disabledParkings[i];
						obj[0] = dpk.getLotNo();
						obj[1] = dpk.getEmployeeId();
						obj[2] = dpk.getFrom();
						obj[3] = dpk.getTo();
						obj[4] = dpk.getX();
						obj[5] = dpk.getY();
						obj[6] = dpk.getZ();
						obj[7] = dpk.getStatus();
						table.getDtm().addRow(obj);
					}

				}
				JPanel cntPane = new JPanel();
				cntPane.setLayout(new GridLayout(1,1));
				cntPane.add(new JLabel("Total disabled parking : "+new Integer(disabledParkings.length).toString()));
				pnlQuarterReports.getPnlTable().add(cntPane,BorderLayout.PAGE_START);
				pnlQuarterReports.getPnlTable().add(table, BorderLayout.CENTER);
			}
			pnlQuarterReports.getPnlTable().revalidate();
			pnlQuarterReports.getPnlTable().repaint();
			pnlQuarterReports.getPnlTable().getParentFrame().pack();

		}else if(func.equals("GetMonthlyReport") && msg.isStatus()){
			VCPScrollTable stable = pnlMonthlyReports.getReportsTable();
			
			String[] header = { "Start week", "Type", "Average",
			            "Median", "Deviation"};
			
			
			DefaultTableModel dtm = new DefaultTableModel(null, header);
			
			stable = new VCPScrollTable(5, dtm);
			//stable.getSelectionModel().addListSelectionListener((ListSelectionListener)this.controller);
			
			Object mdata = msg.getObj();
			WeeklyStatistics[] weekstats = (WeeklyStatistics[]) mdata;
			
			
			if (weekstats.length > 0 ) {
				Object obj[] = new Object[stable.getTable().getColumnCount()];
				Object[] gscale = new Object[weekstats.length];
				for (int i = 0; i < weekstats.length; i++) {
					WeeklyStatistics ws = weekstats[i];				    
					Date myDate=new Date(ws.getStartWeek().getTime());
				    @SuppressWarnings("deprecation")
					//show only the date without time
				    Date dateWithoutTime = new Date(myDate.getYear(),myDate.getMonth(),myDate.getDate());
				    obj[0]= dateWithoutTime;
				    obj[1] = ws.getReportName();
				    obj[2] = ws.getAverage();
				    obj[3] = ws.getMedian();
				    obj[4] = ws.getStandardDeviation();
				    dtm.addRow(obj);
				    gscale[i] = ws.getFreq();
				}
				pnlMonthlyReports.setGscale(gscale);
				stable.setDtm(dtm);
				pnlMonthlyReports.setDtm(dtm);
				pnlMonthlyReports.getPnlTableTab().add(stable, BorderLayout.CENTER);
				stable.getSelectionModel().addListSelectionListener((ListSelectionListener) this.controller);
				
			}
		
			pnlMonthlyReports.getPnlTableTab().revalidate();
			pnlMonthlyReports.getPnlTableTab().repaint();
			pnlMonthlyReports.getPnlTableTab().getParentFrame().pack();
			
			
		}
	}

	@Override
	public void addController(Object obj) {
		pnlReportManagement.getBtnCreate().addActionListener(
				(ActionListener) obj);
		pnlReportManagement.getBtnCreate()
				.setActionCommand("CreateReport");

		pnlReports.getTabbedPane().addChangeListener((ChangeListener) obj);

		pnlLotsStats.getBtnGeneratePdf()
				.addActionListener((ActionListener) obj);
		pnlLotsStats.getBtnGeneratePdf().setActionCommand(
				"ExportGetLotByLotNum");
		pnlReports.getTabbedPane().addTab("Lots", null, pnlLotsStats,
				"Lots stats");
		pnlReports.getTabbedPane().setMnemonicAt(0, KeyEvent.VK_1);

		pnlQuarterReports.getBtnCreate()
				.addActionListener((ActionListener) obj);
		pnlQuarterReports.getBtnCreate().setActionCommand("ManagerGetReport");
		pnlMonthlyReports.getBtnShow().addActionListener((ActionListener)obj);
		pnlMonthlyReports.getBtnShow().setActionCommand("ManagerGetMonthlyReport");
		
		this.controller = obj;

	}

	public PnlReportManagement getPnlReportManagement() {
		return pnlReportManagement;
	}

	public PnlReports getPnlReports() {
		return pnlReports;
	}

	public void setPnlReports(PnlReports pnlReports) {
		this.pnlReports = pnlReports;
	}

	public PnlMonthlyReports getPnlMonthlyReports() {
		return pnlMonthlyReports;
	}

	public PnlQuarterReports getPnlQuarterReports() {
		return pnlQuarterReports;
	}

	public PnlLotsStats getPnlLotsStats() {
		return pnlLotsStats;
	}

}